<?php

/*
 * Author->Gyan 
  Copyright (c) 2013 ASR Market Ventures Private Limited. All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are
  met:

 * Redistributions of source code must retain the above copyright
  notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above
  copyright notice, this list of conditions and the following disclaimer
  in the documentation and/or other materials provided with the
  distribution.
 * Neither the name of ASR Market Ventures Private Limited. nor the names of its
  contributors may be used to endorse or promote products derived from
  this software without specific prior written permission.
 * ASR reserves the right to redistribute the source code, binaries,
  derivative works, techniques, documents, designs and other techniques
  used in this framework under a different license.

  For any questions you may contact us at:

  Attn:
  ASR Market Ventures Private Limited

  Contact:
  http://www.skillhippo.com


  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
//Include Php Mailer class globaly

defined('DS') or define('DS', DIRECTORY_SEPARATOR);
define('TEAM_IMAGE_WIDTH', 260); //Skill::Hari for image resize
define('TEAM_IMAGE_HEIGHT', 260); //Skill::Hari for image resize 
define('USER_IMAGE_WIDTH', 200); //Skill::Gyan for image resize
define('USER_IMAGE_HEIGHT', 160); //Skill::Gyan for image resize 
define('USER_IMAGE_THUMB_WIDTH', 68); //Skill::Hari for image resize
define('USER_IMAGE_THUMB_HEIGHT', 48); //Skill::Hari for image resize 
define('USER_IMAGE_PROFILE_WIDTH', 432); //Skill::Hari for image resize
define('USER_IMAGE_PROFILE_HEIGHT', 324); //Skill::Hari for image resize 
define('CLASS_IMAGE_WIDTH', 70); //Skill::Gyan for image resize
define('CLASS_IMAGE_HEIGHT', 70); //Skill::Gyan for image resize 
define('CLASS_IMAGE_SLIDER_WIDTH', 500); //Skill::Gyan for image resize
define('CLASS_IMAGE_SLIDER_HEIGHT', 400); //Skill::Gyan for image resize 
define('skillicious_IMAGE_SLIDER_WIDTH', 240); //Skill::Gyan for image resize
define('skillicious_IMAGE_SLIDER_HEIGHT', 230); //Skill::Gyan for image resize 
define('CLASS_IMAGE_USERLIST_WIDTH', 300); //Skill::Gyan for image resize
define('CLASS_IMAGE_USERLIST_HEIGHT', 240); //Skill::Gyan for image resize 
define('CLASS_IMAGE_CURETED_WIDTH', 201); //Skill::Gyan for image resize
define('CLASS_IMAGE_CURETED_HEIGHT', 377); //Skill::Gyan for image resize 
define('CLASS_IMAGE_HOME_CATEGORY_WIDTH', 200); //Skill::Gyan for image resize
define('CLASS_IMAGE_HOME_CATEGORY_HIEGHT', 160); //Skill::Gyan for image resize
define('CLASS_IMAGE_DETAILS_WIDTH', 450); //Skill::Gyan for image resize
define('CLASS_IMAGE_DETAILS_HEIGHT', 360); //Skill::Gyan for image resize 
define('EMAIL_HOST', 'email-smtp.us-west-2.amazonaws.com');
define('EMAIL_SMTP_AUTH', TRUE);
define('EMAIL_USER_NAME', 'AKIAIMKIR2G4L4X34C6Q');
define('EMAIL_PASSWORD', 'AnK/MiL/ROZrdzlM41TDfd+Y783HxV8VlAXLU/JRTSIy');
define('EMAIL_TO_ADMIN', 'info@skillhippo.com');
define('EMAIL_FROM', 'info@skillhippo.com');
define('COURSE_CLASS_TYPE', 1);
define('CURATED_CLASS_TYPE', 3);
define('LEAD_CLASS_TYPE', 2);
define('HOME_PAGE_TITLE', 'Courses & Workshops | Professional & Recreational Skills | Delhi Gurgaon Noida');
define('SEARCH_CLASS_WEEKEND', 'Weekend');
define('NO_SEARCH_RESULT_FOUND', "Opps ! We can't find what you are looking try new keyword,or drop a your query ");
define('SEARCH_CLASS_KIDS_CLASS', 'Kids Class');
define('SEARCH_CLASS_POST_WORK', 'Post Work');
define('CLASS_NO_SESSION', '0-1');
define('WORK_SHOP_NAME', 'Workshop name:');
define('COURSE_NAME', 'Course name:');
define('TRAINER_RESPONSE_RATE', 'New');
define('SEARCH_CLASS_WEEKEND_VAL', '1'); //this  functionlity will be use when batch date=saturday&sunday
define('SEARCH_CLASS_WEEKEND_SETVAL', '1,2');
define('SEARCH_CLASS_WEEKEND_SET_DAY_SESSION', '1,7');
define('SEARCH_CLASS_KIDS_SET_DAY_SESSION', '17'); //('1=>sunday,2=>Monaday,3=>Tuesday,4=>Wed,5=>Thus,6=>Fri,7=>sa')
define('SEARCH_CLASS_POST_WORK_SET_START_TIME', "'05'");
define('SEARCH_CLASS_POST_WORK_SET_END_TIME', "'10'");
define('SEARCH_CLASS_KIDS_CLASS_VAL', '2'); // this  functionlity will be use when batch user define
define('SEARCH_CLASS_POST_WORK_VAL', '3'); // this  functionlity will be use when batch date and day=monday to friday 
define('REPEAT_CLASS_MONTHLY', 3);
define('NO_REPEAT', 1);
define('shedule_session', '10,11'); //this session define for shedule in datebase skillhippo
define('REPEAT_CLASS_WEEKLY', 2);
define('CUSTOME_SESSION', 4);
define('SEARCH_TYPE_WEEKEND', 'weekend');
define('SEARCH_TYPE_KIDS', 'kids');
define('LITERAL_ENDING_RENDER_PAGE_LIMIT', '12');
define('SEARCH_TYPE_POST_WORK', 'post_work');
define('Disclaimer', '<b>Disclaimer:</b> The venue-batch details are indicative and may change without prior notice. Connect with the trainer to get the latest information.');

define('FACEBOOK_LINK', ' https://www.facebook.com/SkillHippo');
define('TWITTER_LINK', ' https://twitter.com/skillhippo');
define('LINKEDIN_LINK', 'http://skillhippo.com/');
define('FACEBOOK_LINK_TITLE', 'Facebook');
define('TWITTER_LINK_TITLE', 'Twitter');
define('LINKEDIN_LINK_TITLE', 'Linkedn');
define('CONTACT_INFO_MAIL', 'info@skillhippo.com');
define('CONTACT_INFO_PHONE_NO', '011-46061468');
define('BASE_PATH_EDITOR', '/'); //
define('BASE_DOCUMENT_ROOT_PATH_EDITOR', str_replace('/', '\\\\', $_SERVER['DOCUMENT_ROOT'] . getUploadDir() . '/editor-image/')); //
define('BASE_PATH_CLASSTYPE', 'frontend/www/upload/class-type-image/'); //Skill::Gyan this constent use for store the image  
define('Skillicious_IMAGE_PATH', 'frontend/www/upload/skillicious-image/'); //Skill::Gyan this constent use for store the image  
define('SALT', '');
define('skillicious', 'slider_');
define('HASFUNC', 'md5');
define('OUR_FEATURES_TEACHERS', 'EXPERIENCE TEACHERS');
define('OUR_FEATURES_TEACHERS_TEXT', 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore');
define('OUR_FEATURES_CLASSES', 'All Information About Classes');
define('OUR_FEATURES_CLASSES_TEXT', 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore');
define('OUR_FEATURES_FEE', 'Reasonable Fees');
define('OUR_FEATURES_FEE_TEXT', 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore');
define('CURRENT_DATE', date('Y-m-d'));

/**
 * This is the shortcut to Yii::app()->clientScript->registerCssFile
 */
date_default_timezone_set("Asia/Kolkata");

function regCssFile($files, $url = 'css', $addBaseUrl = true) {
    if (!is_array($files))
        $files = array($files);
    foreach ($files as $file) {
        $file = ($addBaseUrl) ? bu($url) . '/' . $file . '.css' : $url . '/' . $file . '.css';
        cs()->registerCssFile($file);
    }
}

/**
 * This is the shotcut to Yii::app()->clientScript->registerCoreScript
 */
function regCoreFile($files) {
    if (!is_array($files))
        $files = array($files);
    foreach ($files as $file)
        cs()->registerCoreScript($file);
}

function cs() {
    return Yii::app()->clientScript;
}

/**
 * This is the shortcut to Yii::app()->db
 * @return CDbConnection
 */
function db() {
    return Yii::app()->db;
}

/**
 * This is the shortcut to Yii::app()->getRequest
 * @return CHttpRequest object
 */
function getRequest() {
    return Yii::app()->getRequest();
}

/**
 * This is the shortcut to Yii::app()->clientScript->registerScriptFile
 */
function regJsFile($files, $url = 'js', $pos = CClientScript::POS_HEAD) {
    if (!is_array($files))
        $files = array($files);
    foreach ($files as $file)
        cs()->registerScriptFile(bu($url) . '/' . $file . '.js', $pos);
}

/**
 * Shortcut to display Icon image
 * @param string $img image file
 * @param string $size
 * @param string $options
 */
function icon($img, $size = '48', $options = array()) {
    return img(bu('/images/icons/' . $size . '/' . $img), '', $size, null, $options);
}

//getDateTime


function getDateTime($time) {
    return ($time == '') ? 'No data' : date("Y-m-d", $time);
}

/**
 * Displays a variable.
 * This method achieves the similar functionality as var_dump and print_r
 * but is more robust when handling complex objects such as Yii controllers.
 * @param mixed variable to be dumped
 * @param integer maximum depth that the dumper should go into the variable. Defaults to 10.
 * @param boolean whether the result should be syntax-highlighted
 */
function dump($target, $depth = 10, $highlight = true) {
    echo CVarDumper::dumpAsString($target, $depth, $highlight);
}

/**
 * This is the shortcut to CHtml::encode
 */
function h($text, $limit = 0) {
    if ($limit && strlen($text) > $limit && ($pos = strrpos(substr($text, 0, $limit), ' ')) !== false)
        $text = substr($text, 0, $pos) . ' ...';
    return htmlspecialchars($text, ENT_QUOTES, Yii::app()->charset);
}

/**
 * Skill::Gyan
 * This is the shortcut to nl2br(CHtml::encode())
 * @param string the text to be formatted
 * @param integer the maximum length of the text to be returned. If 0, it means no truncation.
 * @param string the label of the "read more" button if $limit is greater than 0.
 * Set this to be false if the "read more" button should not be displayed.
 * @return string the formatted text
 */
function nh($text, $limit = 0, $readMore = 'read more') {
    if ($limit && strlen($text) > $limit) {
        if (($pos = strpos($text, ' ', $limit)) !== false)
            $limit = $pos;
        $ltext = substr($text, 0, $limit);
        if ($readMore !== false) {
            $rtext = substr($text, $limit);
            return nl2br(htmlspecialchars($ltext, ENT_QUOTES, Yii::app()->charset))
                    . ' ' . l(h($readMore), '#', array('class' => 'read-more', 'onclick' => '$(this).hide().next().show(); return false;'))
                    . '<span style="display:none;">'
                    . nl2br(htmlspecialchars($rtext, ENT_QUOTES, Yii::app()->charset))
                    . '</span>';
        }
        else
            return nl2br(htmlspecialchars($ltext . ' ...', ENT_QUOTES, Yii::app()->charset));
    }
    else
        return nl2br(htmlspecialchars($text, ENT_QUOTES, Yii::app()->charset));
}

/**
 *  Skill::Gyan
 * This is the shortcut to CHtmlPurifier::purify().
 */
function ph($text) {
    static $purifier;
    if ($purifier === null)
        $purifier = new CHtmlPurifier;
    return $purifier->purify($text);
}

/**
 * Skill::Gyan
 * Converts a markdown text into purified HTML
 */
function mh($text) {
    static $parser;
    if ($parser === null)
        $parser = new MarkdownParser;
    return $parser->safeTransform($text);
}

/**
 * This is the shortcut to CHtml::link()
 */
function l($text, $url = '#', $htmlOptions = array()) {
    return CHtml::link($text, $url, $htmlOptions);
}

/**
 * Generates an image tag.
 * @param string $url the image URL
 * @param string $alt the alt text for the image. Images should have the alt attribute, so at least an empty one is rendered.
 * @param integer the width of the image. If null, the width attribute will not be rendered.
 * @param integer the height of the image. If null, the height attribute will not be rendered.
 * @param array additional HTML attributes (see {@link tag}).
 * @return string the generated image tag
 */
function img($url, $alt = '', $width = null, $height = null, $htmlOptions = array()) {
    $htmlOptions['src'] = $url;
    if ($alt !== null)
        $htmlOptions['alt'] = $alt;
    else
        $htmlOptions['alt'] = '';
    if ($width !== null)
        $htmlOptions['width'] = $width;
    if ($height !== null)
        $htmlOptions['height'] = $height;
    return CHtml::tag('img', $htmlOptions);
}

/**
 * Skill::Gyan
 * This is the shortcut to Yii::t().
 * Note that the category parameter is removed from the function.
 * It defaults to 'application'. If a different category needs to be specified,
 * it should be put as a prefix in the message, separated by '|'.
 * For example, t('backend|this is a test').
 */
function t($message, $params = array(), $source = null, $language = null) {
    if (($pos = strpos($message, '|')) !== false) {
        $category = substr($message, 0, $pos);
        $message = substr($message, $pos + 1);
    }
    else
        $category = 'application';
    return Yii::t($category, $message, $params, $source, $language);
}

/**
 * This is the shortcut to Yii::app()->createUrl()
 */
function url($route, $params = array(), $ampersand = '&') {
    return Yii::app()->getUrlManager()->createUrl($route, $params, $ampersand);
}

/* Skill::Gyan
 * This is the shortcut to Yii::app()->request->baseUrl
 * If the parameter is given, it will be returned and prefixed with the app baseUrl.
 */

function baseUrl($url = '') {
    static $baseUrl;
    if ($baseUrl === null)
        $baseUrl = Yii::app()->request->baseUrl;
    return $baseUrl . '/' . ltrim($url, '/');
}

/* Skill::Gyan
 * this function use get base url bith path
 * */

function baseUrlClassType($url = null) {
    static $baseUrl;
    if ($baseUrl === null)
        $baseUrl = Yii::app()->getRequest()->getBaseUrl(true) . '/../../' . BASE_PATH_CLASSTYPE;
    return $url === null ? $baseUrl : $baseUrl . '/' . ltrim($url, '/');
}

/* Skill::Gyan  this function use change status any table */

function changeStatusIngridView($data) {
    return ($data->status == 1) ? CHtml::image(getRequestbaseUrl() . "/images/active.png", "Active", array("title" => "Mark Inactive", "style" => "cursor:pointer", "onclick" => "ChangeStatus(" . $data->id . ",0)")) : CHtml::image(getRequestbaseUrl() . "/images/deactive.png", "Inactive", array("title" => "Mark Active", "style" => "cursor:pointer", "onclick" => "ChangeStatus(" . $data->id . ",1)"));
}

function gotohomePage($data) {
    return ($data->go_to_home == 1) ? CHtml::image(getRequestbaseUrl() . "/images/active.png", "Active", array("title" => "Mark Inactive", "style" => "cursor:pointer", "onclick" => "gotohome(" . $data->id . ",0)")) : CHtml::image(getRequestbaseUrl() . "/images/deactive.png", "Inactive", array("title" => "Mark Active", "style" => "cursor:pointer", "onclick" => "gotohome(" . $data->id . ",1)"));
}

function getRequestbaseUrl() {
    return Yii::app()->getRequest()->getBaseUrl(true);
}

function ClassIngridView($data) {
    return ($data->backend_user_id == 1) ? 'Backend' : 'Frontend';
}

function getuploadFolderDir() {
    return '/upload/';
}

function changeIsActiveIngridView($data) {
    return ($data->is_active == 1) ? CHtml::image(getRequestbaseUrl() . "/images/active.png", "Active", array("title" => "Mark Inactive", "style" => "cursor:pointer", "onclick" => "ChangeStatus(" . $data->id . ",0)")) : CHtml::image(getRequestbaseUrl() . "/images/deactive.png", "Inactive", array("title" => "Mark Active", "style" => "cursor:pointer", "onclick" => "ChangeStatus(" . $data->id . ",1)"));
}

/** Returns the named application parameter.  This is the shortcut to Yii::app()->params[$name]. */
function param($name) {
    return Yii::app()->params[$name];
}

function ThemePath($return = false) {
    if ($return)
        return Yii::app()->theme->baseUrl;
    else
        echo Yii::app()->theme->baseUrl;
}

/** * Skill::Gyan  This is the shortcut to Yii::app()->user.  @return WebUser */
function user() {
    return Yii::app()->user;
}

/**  Skill::Gyan  This is the shortcut to Yii::app()->user->checkAccess(). */
function allow($operation, $params = array(), $allowCaching = true) {
    return Yii::app()->user->checkAccess($operation, $params, $allowCaching);
}

/**  Skill::Gyan  Ensures the current user is allowed to perform the specified operation.
 * An exception will be thrown if not.
 * This is similar to {@link access} except that it does not return value.
 */
function ensureAllow($operation, $params = array(), $allowCaching = true) {
    if (!Yii::app()->user->checkAccess($operation, $params, $allowCaching))
        throw new CHttpException(403, Yii::t('error', 'You are not allowed to perform this operation.'));
    return true;
}

//Skill::Gyan function use for Shortcut to Yii::app()->format (utilities for formatting structured text)

function format() {
    return Yii::app()->format;
}

/**
 * Shortcut for json_encode
 * NOTE: json_encode exists in PHP > 5.2, so it's safe to use it directly without checking
 * @param array $json the PHP array to be encoded into json array
 * @param int $opts Bitmask consisting of JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_FORCE_OBJECT.
 */
function je($json, $opts = null) {
//return function_exists('json_encode')? json_encode($json) : CJSON::encode($json);
    return json_encode($json, $opts);
}

/**
 * Shortcut for json_decode
 * NOTE: json_encode exists in PHP > 5.2, so it's safe to use it directly without checking
 * @param string $json the PHP array to be decoded into json array
 * @param bool $assoc when true, returned objects will be converted into associative arrays.
 * @param int $depth User specified recursion depth.
 * @param int $opts Bitmask of JSON decode options. 
 * 	Currently only JSON_BIGINT_AS_STRING is supported 
 * 	(default is to cast large integers as floats)
 */
function jd($json, $assoc = null, $depth = 512, $opts = 0) {
    return json_decode($json, $assoc, $depth);
}

/**
 * Adds trailing dots to a string if exceeds the length specified
 * @param string $txt the text to cut
 * @param integer $length the length
 * @param string $encoding the encoding type if multibyte, null otherwise
 * @return string 
 */
function trail($txt, $length, $encoding = 'utf-8') {
    if (strlen($txt) > $length) {
        if (null != $encoding) {
            $txt = mb_substr($txt, 0, $length - 3, $encoding);
            $pos = mb_strrpos($txt, ' ', null, $encoding);
            $txt = mb_substr($txt, 0, $pos, $encoding) . '...';
        } else {
            $txt = substr($txt, 0, $length - 3);
            $pos = strrpos($txt, ' ');
            $txt = substr($txt, 0, $pos) . '...';
        }
    }
    return $txt;
}

function obfuscateEmail($address) {
    $address = strtolower($address);
    $coded = "";
    $unmixedkey = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.@";
    $inprogresskey = $unmixedkey;
    $mixedkey = "";
    $unshuffled = strlen($unmixedkey);
    for ($i = 0; $i <= strlen($unmixedkey); $i++) {
        $ranpos = rand(0, $unshuffled - 1);
        $nextchar = substr($inprogresskey, $ranpos, 1);
        $mixedkey .= $nextchar;
        $before = substr($inprogresskey, 0, $ranpos);
        $after = substr($inprogresskey, $ranpos + 1, $unshuffled - ($ranpos + 1));
        $inprogresskey = $before . '' . $after;
        $unshuffled -= 1;
    }
    $cipher = $mixedkey;

    $shift = strlen($address);

    $txt = "<script type=\"text/javascript\" language=\"javascript\">\n" .
            "<!-" . "-\n";

    for ($j = 0; $j < strlen($address); $j++) {
        if (strpos($cipher, $address{$j}) == -1) {
            $chr = $address{$j};
            $coded .= $chr;
        } else {
            $chr = (strpos($cipher, $address{$j}) + $shift) % strlen($cipher);
            $coded .= $cipher{$chr};
        }
    }


    $txt .= "\ncoded = \"" . $coded . "\"\n" .
            "  key = \"" . $cipher . "\"\n" .
            "  shift=coded.length\n" .
            "  link=\"\"\n" .
            "  for (i=0; i<coded.length; i++) {\n" .
            "    if (key.indexOf(coded.charAt(i))==-1) {\n" .
            "      ltr = coded.charAt(i)\n" .
            "      link += (ltr)\n" .
            "    }\n" .
            "    else {     \n" .
            "      ltr = (key.indexOf(coded.charAt(i))-
shift+key.length) % key.length\n" .
            "      link += (key.charAt(ltr))\n" .
            "    }\n" .
            "  }\n" .
            "document.write(\"<a href='mailto:\"+link+\"'>\"+link+\"</a>\")\n" .
            "\n" .
            "//-" . "->\n" .
            "<" . "/script><noscript>N/A" .
            "<" . "/noscript>";
    return $txt;
}

//Skill::Gyan function use for debug purpose
function pr($arr, $die = true) {
    echo "<pre>";
    print_r($arr);
    echo "</pre>";
    if ($die) {
        die();
    }
}

//Skill::Gyan function use return upload dir
function getUploadDir() {
    return 'frontend/www/upload/';
}
function getFrontDir(){
    return SITE_URL.'upload/';
}
function getBackDir(){
    return SITE_URL.'upload/backend/';
}


//Skill::Hari function use return upload dir
function getUploadDirBackend() {
    return 'frontend/www/upload/backend/';
}

//Skill::Gyan Getlginuser id
function getLoginUserId() {
    return Yii::app()->user->id;
}

//Skill::Gyan function use for generate rendom string
function guid() {
    if (function_exists('com_create_guid')) {
        $guid = com_create_guid();
        $guid = preg_replace("/[^A-Za-z0-9]/", "", $guid);
        return $guid;
    } else {
        mt_srand((double) microtime() * 10000); //optional for php 4.2.0 and up.
        $charid = strtoupper(md5(uniqid(rand(), true)));
        $guid = substr($charid, 0, 8)
                . substr($charid, 8, 4)
                . substr($charid, 12, 4)
                . substr($charid, 16, 4)
                . substr($charid, 20, 12);
        return $guid;
    }
}

function getAllSchedule($type) {
    if ($type == "course") {
        $condition = ' id NOT IN ( 1, 2, 3, 4 ) AND status =  ' . SkillConfig::STATUS_ACTIVE;
        $options = ClassSchedule::model()->findAll(array('condition' => $condition));
    } else {
        $condition = ' id IN ( 1, 2, 3, 4 ) AND status =  ' . SkillConfig::STATUS_ACTIVE;
        $options = ClassSchedule::model()->findAll(array('condition' => $condition));
    }
    /* $options = ClassSchedule::model()->findAllByAttributes(array('status' => SkillConfig::STATUS_ACTIVE)); */
    return CHtml::listData($options, 'id', 'name');
}

function getVenueByUser($model) {
    $data = $model->findAll('users_id=:users_id', array(':users_id' => (int) getLoginUserId()));
    return CHtml::listData($data, 'id', 'name');
}

function getVenueByBackendUser($model) {
    $frontUser = (Yii::app()->session['trainer_id']) ? Yii::app()->session['trainer_id'] : '';
    if (!empty($frontUser)) {
        $data = $model->findAll('users_id=:users_id', array(':users_id' => (int) $frontUser));
    } else {
        $data = $model->findAll('backend_user_id=:backend_user_id', array(':backend_user_id' => (int) getLoginUserId()));
    }
    return CHtml::listData($data, 'id', 'name');
}

function getAllTargetAudience($id, $type) {
    $selectedOptionsTargetAudience = array();
    $TargetAudienceValues = '';
    $modelTargetAudience = new ClassesTargetAudience();
    if ($type <> "" && $id <> "") {
        if ($type == "class") {
            $TargetAudienceValues = $modelTargetAudience->findAllByAttributes(array('classes_id' => $id));
        } else {
            $TargetAudienceValues = $modelTargetAudience->findAllByAttributes(array('courses_id' => $id));
        }
    }
    if ($TargetAudienceValues) {
        foreach ($TargetAudienceValues as $eachValue) {
            $selectedOptionsTargetAudience[$eachValue->target_audience_id] = array('selected' => 'selected');
        }
    }
    return $selectedOptionsTargetAudience;
}

function getAllTags($id, $type) {

    $selectedOptionsClassCoursetag = array();
    if ($type <> "" && $id <> "") {
        if ($type == "class") {
            $classCourseTag = getClaCourseInfo('Classes', $id);
            $classtag = !empty($classCourseTag) ? explode(',', $classCourseTag->class_tag) : '';
        } else {
            $classCourseTag = getClaCourseInfo('Courses', $id);
            $classtag = !empty($classCourseTag) ? explode(',', $classCourseTag->course_tag) : '';
        }
    }
    if (!empty($classtag)) {
        $criteria = new CDbCriteria;
        $criteria->addInCondition('id', $classtag);
        $classCoursetagArray = ClassCourseTags::model()->findAll($criteria);
        foreach ($classCoursetagArray as $key => $eachValue) {
            $selectedOptionsClassCoursetag[$eachValue->id] = array('selected' => 'selected');
        }
        return $selectedOptionsClassCoursetag;
    }
}

function numberofDays() {
    $str = '';
    for ($i = 0; $i < 31; $i++) {
        $str = $str . $i . ',';
    }
    $str = trim($str, ",");
    return explode(',', $str);
}

function numberofTimings() {
    $str = '';
    for ($i = 1; $i < 25; $i++) {
        $str = $str . $i . ',';
    }
    $str = trim($str, ",");
    return explode(',', $str);
}

function numberofTimingsFrame() {
    $nooftiming = numberofTimings();
    for ($i = 0; $i < count($nooftiming); $i++) {
        if ($nooftiming[$i] > 12) {
            $nooftiming[$i] = $nooftiming[$i] - 12;
            $ampm = 'PM';
        } else {
            $ampm = 'AM';
        }
        echo '<option value="' . $nooftiming[$i] . " " . $ampm . '">' . $nooftiming[$i] . " " . $ampm . '</option>';
    }
}

/**
 * This function is used for password encryption.
 * @return hash string.
 */
function encrypt($string = "") {
    $salt = SALT;
    $hashFunc = HASFUNC;
    $string = sprintf("%s%s%s", $salt, $string, $salt);

    if (!function_exists($hashFunc))
        throw new CException('Function `' . $hashFunc . '` is not a valid callback for hashing algorithm.');

    return $hashFunc($string);
}

/* Create folders for upload images: Hari */

function makeUploadDir($utype = '') {
    $pos = strrpos($utype, "/");
    if ($pos <> "") { // note: three equal signs
        $udata = explode("/", $utype);
        $folder = getUploadDirBackend() . $udata[1];
        @mkdir(getUploadDirBackend(), 0777);
    } else {
        if ($utype == "backend") {
            $folder = getUploadDirBackend() . getLoginUserId();
            @mkdir(getUploadDirBackend(), 0777);
        } else {
            $folder = getUploadDir() . getLoginUserId();
        }
    }

    $dirUser = $folder;
    $dirProfile = $dirUser . '/profile';
    $dirProfileThumb = $dirUser . '/profile/thumb';
    $dirProfileMiniThumb = $dirUser . '/profile/minithumb';
    $dirProfileMain = $dirUser . '/profile/432X324';
    $dirClassCourse = $dirUser . '/class-course-image';
    $dirClassCourseDetail = $dirUser . '/class-course-image/details-image';
    $dirClassCourseImage = $dirUser . '/class-course-image/image';
    $dirClassCourseSlider = $dirUser . '/class-course-image/slider-image';
    $dirClassCourseThumb = $dirUser . '/class-course-image/thumbs';
    $dirClassCourseUserView = $dirUser . '/class-course-image/240X180';
    $dirClassCourseCuretedClass = $dirUser . '/class-course-image/201X377';
    $homecategory = $dirUser . '/class-course-image/207X145';
    $dirEditor = $dirUser . '/editor-image';
    $dirEditorImage = $dirUser . '/editor-image/images';

    @mkdir($dirUser, 0777);
    @mkdir($dirProfile, 0777);
    @mkdir($dirProfileThumb, 0777);
    @mkdir($dirProfileMiniThumb, 0777);
    @mkdir($dirProfileMain, 0777);
    @mkdir($dirClassCourse, 0777);
    @mkdir($dirClassCourseDetail, 0777);
    @mkdir($dirClassCourseImage, 0777);
    @mkdir($dirClassCourseSlider, 0777);
    @mkdir($dirClassCourseThumb, 0777);
    @mkdir($dirClassCourseUserView, 0777);
    @mkdir($dirEditor, 0777);
    @mkdir($dirEditorImage, 0777);
    @mkdir($dirClassCourseCuretedClass, 0777);
    @mkdir($homecategory, 0777);
}

function makeUploadDirCreateUsers($utype = '', $usersId) {
    $pos = strrpos($utype, "/");
    if ($pos <> "") { // note: three equal signs
        $udata = explode("/", $utype);
        $folder = getUploadDirBackend() . $udata[1];
        @mkdir(getUploadDirBackend(), 0777);
    } else {
        if ($utype == "backend") {
            $folder = getUploadDirBackend() . getLoginUserId();
            @mkdir(getUploadDirBackend(), 0777);
        } else {
            $folder = getUploadDir() . $usersId;
        }
    }

    $dirUser = $folder;
    $dirProfile = $dirUser . '/profile';
    $dirProfileThumb = $dirUser . '/profile/thumb';
    $dirProfileMiniThumb = $dirUser . '/profile/minithumb';
    $dirProfileMain = $dirUser . '/profile/432X324';
    $dirClassCourse = $dirUser . '/class-course-image';
    $dirClassCourseDetail = $dirUser . '/class-course-image/details-image';
    $dirClassCourseImage = $dirUser . '/class-course-image/image';
    $dirClassCourseSlider = $dirUser . '/class-course-image/slider-image';
    $dirClassCourseThumb = $dirUser . '/class-course-image/thumbs';
    $dirClassCourseUserView = $dirUser . '/class-course-image/240X180';
    $dirEditor = $dirUser . '/editor-image';
    $dirEditorImage = $dirUser . '/editor-image/images';
    $dirClassCourseCuretedClass = $dirUser . '/class-course-image/201X377';
    $homecategory = $dirUser . '/class-course-image/207X145';

    @mkdir($dirUser, 0777);
    @mkdir($dirProfile, 0777);
    @mkdir($dirProfileThumb, 0777);
    @mkdir($dirProfileMiniThumb, 0777);
    @mkdir($dirProfileMain, 0777);
    @mkdir($dirClassCourse, 0777);
    @mkdir($dirClassCourseDetail, 0777);
    @mkdir($dirClassCourseImage, 0777);
    @mkdir($dirClassCourseSlider, 0777);
    @mkdir($dirClassCourseThumb, 0777);
    @mkdir($dirClassCourseUserView, 0777);
    @mkdir($dirEditor, 0777);
    @mkdir($dirEditorImage, 0777);
    @mkdir($dirClassCourseCuretedClass, 0777);
    @mkdir($homecategory, 0777);
}

/* Show date time ago */

function TimeAgo($datefrom, $dateto = -1) {
    if ($datefrom <= 0) {
        return "A long time";
    }
    if ($dateto == -1) {
        $dateto = time();
    }
    $difference = $dateto - $datefrom;
    if ($difference < 60) {
        $interval = "s";
    } elseif ($difference >= 60 && $difference < 60 * 60) {
        $interval = "n";
    } elseif ($difference >= 60 * 60 && $difference < 60 * 60 * 24) {
        $interval = "h";
    } elseif ($difference >= 60 * 60 * 24 && $difference < 60 * 60 * 24 * 7) {
        $interval = "d";
    } elseif ($difference >= 60 * 60 * 24 * 7 && $difference < 60 * 60 * 24 * 30) {
        $interval = "ww";
    } elseif ($difference >= 60 * 60 * 24 * 30 && $difference < 60 * 60 * 24 * 365) {
        $interval = "m";
    } elseif ($difference >= 60 * 60 * 24 * 365) {
        $interval = "y";
    }
    switch ($interval) {
        case "m":
            $months_difference = floor($difference / 60 / 60 / 24 / 29);
            while (mktime(date("H", $datefrom), date("i", $datefrom), date("s", $datefrom), date("n", $datefrom) + ($months_difference), date("j", $dateto), date("Y", $datefrom)) < $dateto) {
                $months_difference++;
            }
            $datediff = $months_difference;
            if ($datediff == 12) {
                $datediff--;
            }

            $res = ($datediff == 1) ? "$datediff month" : "$datediff
		Months";
            break;

        case "y":
            $datediff = floor($difference / 60 / 60 / 24 / 365);
            $res = ($datediff == 1) ? "$datediff year" : "$datediff Years";
            break;

        case "d":
            $datediff = floor($difference / 60 / 60 / 24);
            $res = ($datediff == 1) ? "$datediff day" : "$datediff Days";
            break;

        case "ww":
            $datediff = floor($difference / 60 / 60 / 24 / 7);
            $res = ($datediff == 1) ? "$datediff week" : "$datediff Weeks";
            break;

        case "h":
            $datediff = floor($difference / 60 / 60);
            $res = ($datediff == 1) ? "$datediff hour" : "$datediff Hrs";
            break;

        case "n":
            $datediff = floor($difference / 60);
            $res = ($datediff == 1) ? "$datediff minute" : "$datediff Mins";
            break;

        case "s":
            $datediff = $difference;
            $res = ($datediff == 1) ? "$datediff second" : "$datediff seconds";
            break;
    }
    return $res;
}

/* Show date time ago */
/* convert date time */

function convert_datetime($str) {
    list($date, $time) = explode(' ', $str);
    list($year, $month, $day) = explode('-', $date);
    list($hour, $minute, $second) = explode(':', $time);
    $timestamp = mktime($hour, $minute, $second, $month, $day, $year);
    return $timestamp;
}

function deleteDir($dir) {
    foreach (glob($dir . '/*') as $file) {
        if (is_dir($file))
            deleteDir($file);
    }
    rmdir($dir);
}

function activeClassCategory($type) {
    $active = '';
    if ($type == 'workshop') {
        $active = '1,workshop';
    }
    if ($type == 'course') {
        $active = '0,course';
    }
    if ($type == 'curatedclasses' || $type == 'exclusives') {
        $active = '2,curatedclasses';
    }
    if (!empty($active)) {
        return explode(',', $active);
    }
}

/* coupons start */

function couponArray() {
    return array('1' => 'Order Subtotal&nbsp;', '2' => 'Total of matching products&nbsp;', '3' => 'All matching products&nbsp;', '4' => 'The cheapest matching products&nbsp;', '5' => 'The most expensive matching products&nbsp;');
}

function getAllCouponClassCourse($id, $type) {
    $selectedOptionsClassCourse = array();
    $OptionsClassCourseValues = '';
    $ClassCourseCategoryUsersRestrictionCoupon = new ClassCourseCategoryUsersRestrictionCoupon();
    if ($type <> "" && $id <> "") {
        if ($type == "class") {
            $OptionsClassCourseValues = $ClassCourseCategoryUsersRestrictionCoupon->findAllByAttributes(array('coupons_id' => $id));
            if ($OptionsClassCourseValues) {
                foreach ($OptionsClassCourseValues as $eachValue) {
                    $selectedOptionsClassCourse[$eachValue->classes_id] = array('selected' => 'selected');
                }
            }
        } else {
            $OptionsClassCourseValues = $ClassCourseCategoryUsersRestrictionCoupon->findAllByAttributes(array('coupons_id' => $id));
            if ($OptionsClassCourseValues) {
                foreach ($OptionsClassCourseValues as $eachValue) {
                    $selectedOptionsClassCourse[$eachValue->courses_id] = array('selected' => 'selected');
                }
            }
        }
    }

    return $selectedOptionsClassCourse;
}

//this function use for add aa month from current date;
function addOneMonthinBatch($batchDate) {
    $monthToAdd = 1;
    $d1 = DateTime::createFromFormat('Y-m-d', $batchDate);
    $year = $d1->format('Y');
    $month = $d1->format('n');
    $day = $d1->format('d');
    $monthToAdd = $monthToAdd % 12;
    $month += $monthToAdd;
    if ($month > 12) {
        $year++;
        $month = $month % 12;
        if ($month === 0)
            $month = 12;
    }
    if (!checkdate($month, $day, $year)) {
        $d2 = DateTime::createFromFormat('Y-n-j', $year . '-' . $month . '-1');
        $d2->modify('last day of');
    } else {
        if ($month == 3 && ($day == 29 || $day == 28)) {
            $d2 = DateTime::createFromFormat('Y-n-j', $year . '-' . $month . '-1');
            $d2->modify('last day of this month');
        } else {
            $d2 = DateTime::createFromFormat('Y-n-d', $year . '-' . $month . '-' . $day);
        }
    }
    $d2->setTime($d1->format('H'), $d1->format('i'), $d1->format('s'));
    return $d2->format('Y-m-d');
}

function getUserTypeByClassCourse($model, $id) {
    $model = new $model;
    $modelVal = $model->findByAttributes(array('id' => $id));
    return $userDetails = ($modelVal->users_id == '') ? Users::getBackEndUser($modelVal->backend_user_id) : Users::getFrontEndUser($modelVal->users_id);
}

function getImagePathByClassCourse($model, $id) {
    $model = new $model;
    $modelVal = $model->findByAttributes(array('id' => $id));
    return $userDetails = ($modelVal->users_id == '') ? 'backend/' . $modelVal->backend_user_id : $modelVal->users_id;
}

function getClassName($id) {
    $modelVal = Classes::model()->findByAttributes(array('id' => $id));
    if (!empty($modelVal)) {
        return $modelVal->class_titile;
    }
}

function getClaCourseInfo($model, $id) {
    $model = new $model;
    $modelVal = $model->findByAttributes(array('id' => $id));
    if (!empty($modelVal)) {
        return $modelVal;
    }
}

function getcourseName($id) {
    $modelVal = Courses::model()->findByAttributes(array('id' => $id));
    if (!empty($modelVal)) {
        return $modelVal->course_titile;
    }
}

function peoplelikedClassCourse() {
    $criteria = new CDbCriteria();
    $criteria->condition = ('status=' . SkillConfig::STATUS_ACTIVE . ' AND classes_id  IS NOT NULL OR courses_id  IS NOT NULL');
    $criteria->group = 'classes_id ,courses_id';
    $model = ClassCourseTrainnerRate::model()->findAll($criteria);
    return $model;
}

function previousClassCourseByuser($profiles, $userType) {
    $courseArray = array();
    $classArray = array();
    $userid_type = ($userType != 'backend') ? 'users_id' : 'backend_user_id';
    $date = date('Y-m-d');
    $command = Yii::app()->db->createCommand();
    $command->select('t.course_seo_title,scb.price,t.users_id,t.backend_user_id,scb.courses_id,t.course_titile,scb.date_from,t.course_type_id,scb.date_to,scwv.course_venue_id');
    $command->from('skill_courses t LEFT JOIN skill_course_batche scb ON (t.id = scb.courses_id) LEFT JOIN skill_course_with_venue scwv ON (t.id = scwv.courses_id)');
    $command->where('t.' . $userid_type . '=' . $profiles->user_id . ' AND t.status="' . SkillConfig::STATUS_ACTIVE . '" AND scb.date_to<"' . $date . '"');
    $command->order('scb.date_from ASC');
    $command->group('scb.courses_id');
    $rawDatas = $command->queryAll();
    foreach ($rawDatas as $rawData) {
        $courseArray[] = array('id' => $rawData['courses_id'], 'course_seo_title' => $rawData['course_seo_title'], 'course_venue_id' => $rawData['course_venue_id'], 'front-user' => $rawData['users_id'], 'backend-user' => $rawData['backend_user_id'], 'course_type_id' => $rawData['course_type_id'], 'courses_id' => $rawData['courses_id'], 'course_titile' => $rawData['course_titile'], 'start_date' => $rawData['date_from'], 'end_date' => $rawData['date_to']);
    }

    $classCommand = Yii::app()->db->createCommand();
    $classCommand->select = ('t.class_seo_title,scwv.class_venue_id,scb.start_date,t.class_type_id,t.class_titile,scb.classes_id, t.users_id,t.backend_user_id');
    $classCommand->from('skill_classes t LEFT JOIN skill_class_batch scb ON (t.id = scb.classes_id) LEFT JOIN skill_batche_session sbs ON (t.id = sbs.classes_id) LEFT JOIN skill_class_with_venue scwv ON (t.id = scwv.classes_id)');
    $classCommand->where('t.' . $userid_type . '=' . $profiles->user_id . ' AND t.status="' . SkillConfig::STATUS_ACTIVE . '" AND (scb.start_date<"' . $date . '" AND sbs.date<"' . $date . '") AND (scb.schedule_id=4 OR scb.schedule_id=1)');
    $classCommand->order('scb.start_date ASC');
    $classCommand->group('scb.classes_id');
    $classDatas = $classCommand->queryAll();
    foreach ($classDatas as $classData) {
        $classArray[] = array('id' => $classData['classes_id'], 'front-user' => $classData['users_id'],
            'backend-user' => $classData['backend_user_id'],
            'class_type_id' => $classData['class_type_id'],
            'class_venue_id' => $classData['class_venue_id'],
            'classes_id' => $classData['classes_id'],
            'class_seo_title' => $classData['class_seo_title'],
            'class_titile' => $classData['class_titile'], 'start_date' => $classData['start_date']);
    }

    $classCourseArray = array_merge($courseArray, $classArray);
    usort($classCourseArray, 'date_compare');
    return $classCourseArray;
}

function previousClassByuser($profiles, $userType) {
    $classArray = array();
    $userid_type = ($userType != 'backend') ? 'users_id' : 'backend_user_id';
    $date = date('Y-m-d');
    $classCommand = Yii::app()->db->createCommand();
    $classCommand->select = ('t.class_seo_title,t.hits_counter,scwv.class_venue_id,scb.start_date,scb.price,t.class_type_id,t.class_titile,scb.classes_id, t.users_id,t.backend_user_id');
    $classCommand->from('skill_classes t LEFT JOIN skill_class_batch scb ON (t.id = scb.classes_id) LEFT JOIN skill_batche_session sbs ON (t.id = sbs.classes_id) LEFT JOIN skill_class_with_venue scwv ON (t.id = scwv.classes_id)');
    $classCommand->where('t.' . $userid_type . '=' . $profiles->user_id . ' AND t.status="' . SkillConfig::STATUS_ACTIVE . '" AND (scb.start_date<"' . $date . '" AND sbs.date<"' . $date . '") AND (scb.schedule_id=4 OR scb.schedule_id=1) AND scb.start_date<"' . $date . '"');
    $classCommand->order('scb.start_date ASC');
    $classCommand->group('scb.classes_id');
    $classDatas = $classCommand->queryAll();
    foreach ($classDatas as $classData) {
        $classArray[] = array('id' => $classData['classes_id'], 'front-user' => $classData['users_id'],
            'backend-user' => $classData['backend_user_id'], 'hits_counter' => $classData['hits_counter'],
            'class_type_id' => $classData['class_type_id'],
            'class_venue_id' => $classData['class_venue_id'],
            'classes_id' => $classData['classes_id'],
            'class_seo_title' => $classData['class_seo_title'],
            'class_titile' => $classData['class_titile'], 'start_date' => $classData['start_date'], 'price' => $classData['price']);
    }
    $classCourseArray = $classArray;
    usort($classCourseArray, 'date_compare');
    return $classCourseArray;
}

function previousCourseByuser($profiles, $userType) {
    $courseArray = array();
    $classArray = array();
    $userid_type = ($userType != 'backend') ? 'users_id' : 'backend_user_id';
    $date = date('Y-m-d');
    $command = Yii::app()->db->createCommand();
    $command->select('t.course_seo_title,scb.price,t.hits_counter,t.users_id,t.backend_user_id,scb.courses_id,scb.price,t.course_titile,scb.date_from,t.course_type_id,scb.date_to,scwv.course_venue_id');
    $command->from('skill_courses t LEFT JOIN skill_course_batche scb ON (t.id = scb.courses_id) LEFT JOIN skill_course_with_venue scwv ON (t.id = scwv.courses_id)');
    $command->where('t.' . $userid_type . '=' . $profiles->user_id . ' AND t.status="' . SkillConfig::STATUS_ACTIVE . '" AND scb.date_to<"' . $date . '"');
    $command->order('scb.date_from ASC');
    $command->group('scb.courses_id');
    $rawDatas = $command->queryAll();
    foreach ($rawDatas as $rawData) {
        $courseArray[] = array('id' => $rawData['courses_id'], 'course_seo_title' => $rawData['course_seo_title'], 'price' => $rawData['price'], 'hits_counter' => $rawData['hits_counter'], 'course_venue_id' => $rawData['course_venue_id'], 'front-user' => $rawData['users_id'], 'backend-user' => $rawData['backend_user_id'], 'course_type_id' => $rawData['course_type_id'], 'courses_id' => $rawData['courses_id'], 'course_titile' => $rawData['course_titile'], 'start_date' => $rawData['date_from'], 'end_date' => $rawData['date_to']);
    }
    $classCourseArray = $courseArray;
    usort($classCourseArray, 'date_compare');
    return $classCourseArray;
}

function rangeWeek($datestr) {
    date_default_timezone_set(date_default_timezone_get());
    $dt = strtotime($datestr);
    $res['start'] = date('N', $dt) == 1 ? date('Y-m-d', $dt) : date('Y-m-d', strtotime('last monday', $dt));
    $res['end'] = date('N', $dt) == 7 ? date('Y-m-d', $dt) : date('Y-m-d', strtotime('next sunday', $dt));
    return $res;
}

function date_compare($a, $b) {
    $t1 = strtotime($a['start_date']);
    $t2 = strtotime($b['start_date']);
    return $t1 - $t2;
}
function date_compare_ASC($a, $b){
    $t1 = strtotime($a['start_date']);
    $t2 = strtotime($b['start_date']);
    return $t2 - $t1;
}

function price_compare_descending($a, $b) {
    $t1 = $a['price'];
    $t2 = $b['price'];
    return $t2 > $t1;
}

function price_compare_ascending($a, $b) {
    $t1 = $a['price'];
    $t2 = $b['price'];
    return $t1 > $t2;
}

function shoppingcart_compare_price($x, $y) {
    return ($x['price'] < $y['price']);
}

function hitcounter_compare_descending($a, $b) {
    $t1 = ($a['hits_counter']);
    $t2 = ($b['hits_counter']);
    return $t2 > $t1;
}

function hitcounter_compare_ascending($a, $b) {
    $t1 = $a['hits_counter'];
    $t2 = $b['hits_counter'];
    return $t2 > $t1;
}

function getAllDatesInCurrentWeek($startDate, $endDate) {
    while (strtotime($startDate) <= strtotime($endDate)) {
        $allDate[] = $startDate;
        $startDate = date("Y-m-d", strtotime("+1 day", strtotime($startDate)));
    }
    return $allDate;
}

function runningCurrentCoursesByUser($profiles, $userType, $getValue) {
    $courseArray = array();
    $leftjoin = '';
    $orderBy = '';
    $userid_type = ($userType != 'backend') ? 'users_id' : 'backend_user_id';
    $date = date('Y-m-d');
    if (!empty($profiles) && !empty($userid_type)) {
        $where = 'sc.' . $userid_type . '=' . $profiles->user_id . '   AND sc.status="' . SkillConfig::STATUS_ACTIVE . '" AND scb.date_to>="' . $date . '"';
    } else {
        $where = 'sc.status="' . SkillConfig::STATUS_ACTIVE . '"   AND scb.date_to>="' . $date . '"';
    }
    if (isset($getValue['searchtype']) && $getValue['searchtype'] == SEARCH_TYPE_KIDS) {
        $leftjoin = 'LEFT JOIN skill_classes_target_audience scta  ON (t.courses_id=scta.courses_id)';
        $where .='  AND scta.target_audience_id=' . SEARCH_CLASS_KIDS_SET_DAY_SESSION;
    }

    if (empty($getValue['searchtype']) && isset($getValue['postwork']) && !empty($getValue['postwork'])) {
        $leftjoin = 'LEFT JOIN skill_classes_target_audience scta  ON (t.courses_id=scta.courses_id)';
        $where .='  AND scta.target_audience_id!=' . SEARCH_CLASS_KIDS_SET_DAY_SESSION;
    }


    if (!empty($getValue['location'])) {
        $location = $getValue['location'];
        $where .=' AND t.course_venue_id=' . $location;
    }

    if (!empty($getValue['priceorder'])) {
        $orderBy .=($getValue['priceorder'] == 1) ? ' scb.price ASC ,' : ' scb.price DESC , ';
    }
    if (!empty($getValue['mostpopular'])) {
        $orderBy .=($getValue['mostpopular'] == 1) ? '  sc.hits_counter DESC ' : '';
    }
    if (!empty($getValue['category'])) {
        $where .=' AND sc.category_id IN (' . $getValue['category'] . ')';
    }

    if (!empty($getValue['amountRange'])) {
        $price = explode(',', $getValue['amountRange']);
        $where .=' AND scb.price BETWEEN ' . $price[0] . ' AND ' . $price[1];
    }
    if (!empty($getValue['dateFrom']) AND !empty($getValue['dateto'])) {
        $dateFrom = $getValue['dateFrom'];
        $dateto = $getValue['dateto'];
        $where .=' AND scb.date_to BETWEEN "' . $dateFrom . '" AND "' . $dateto . '"';
    }
// scheduleId means this is weekend otherwise Kids Class course
    if (!empty($getValue['scheduleId'])) {
        $where .=' AND (DAYOFWEEK(scb.date_from) IN (' . $getValue['scheduleId'] . ')  OR  (DAYOFWEEK(cbds.date) IN (' . $getValue['scheduleId'] . '))   OR   scbds.schedule_id IN (' . shedule_session . '))';
    }
    if (isset($getValue['postwork']) && !empty($getValue['postwork'])) {
        $where .=' AND (LEFT(cbds.time_from,2)>=' . SEARCH_CLASS_POST_WORK_SET_START_TIME . ' AND LEFT(cbds.time_from,2)<=' . SEARCH_CLASS_POST_WORK_SET_END_TIME . ' AND RIGHT(cbds.time_from,2)="PM"   OR  LEFT(scbds.time_from,2)>=' . SEARCH_CLASS_POST_WORK_SET_START_TIME . ' AND LEFT(scbds.time_from,2)<=' . SEARCH_CLASS_POST_WORK_SET_END_TIME . ' AND RIGHT(scbds.time_from,2)="PM")';
    }
    if (!empty($getValue['learn'])) {
        $learn = $getValue['learn'];
        $vark = explode(' ', $learn);
        $endVal = end($vark);
        $endKey = key($vark);
        $localityVal = ($endKey > 0) ? $vark[$endKey - 1] . ' ' . $endVal : $endVal;
        $where .=' AND (sc.course_tag_description LIKE "%' . $learn . '%" OR sc.course_titile  LIKE "%' . $learn . '%" OR sc.course_description  LIKE "%' . $learn . '%" OR  sc.course_short_description  LIKE "%' . $learn . '%"  OR sc.course_outcome  LIKE "%' . $learn . '%" OR sc.course_prerequisites  LIKE "%' . $learn . '%" OR scv.venue_locality  LIKE "%' . $localityVal . '%")';
    }
    $command = Yii::app()->db->createCommand();
    $command->select('sc.course_seo_title,sc.hits_counter,scb.price,sc.users_id,sc.backend_user_id,scb.courses_id,sc.course_titile,scb.date_from,sc.course_type_id,scb.date_to,t.courses_id,t.course_venue_id');
    $command->from('skill_course_with_venue t left join skill_class_venue scv on (t.course_venue_id=scv.id)  left join skill_courses sc on (t.courses_id=sc.id) LEFT JOIN skill_course_batche scb ON (t.courses_id = scb.courses_id  AND t.course_venue_id=scb.course_venue_id) LEFT JOIN  skill_course_batche_date_session  cbds ON   (cbds.course_batche_id=scb.id  AND t.courses_id = cbds.courses_id) LEFT JOIN skill_course_batche_day_session scbds ON (scbds.course_batche_id=scb.id AND scb.courses_id = scbds.courses_id ) ' . $leftjoin);
    $command->where($where);    
    $command->order($orderBy); 
//    echo $command->getText();die;
   // echo $command->getText();die;
    $rawDatas = $command->queryAll();
    foreach ($rawDatas as $rawData) {
        $courseArray[] = array('course_seo_title' => $rawData['course_seo_title'], 'id' => $rawData['courses_id'], 'remove_id' => $rawData['courses_id'] . '-' . $rawData['course_venue_id'], 'course_venue_id' => $rawData['course_venue_id'], 'price' => $rawData['price'], 'hits_counter' => $rawData['hits_counter'], 'front-user' => $rawData['users_id'], 'backend-user' => $rawData['backend_user_id'], 'course_type_id' => $rawData['course_type_id'], 'courses_id' => $rawData['courses_id'], 'course_titile' => $rawData['course_titile'], 'start_date' => $rawData['date_from'], 'end_date' => $rawData['date_to']);
    }   
    $courseArray = get_uniqueValue_in_array($courseArray);
    return $courseArray;
}

function getUserType($model, $id) {
    $model = new $model;
    $modelVal = $model->findByAttributes(array('id' => $id));
    return $userDetails = ($modelVal->users_id == '') ? 'backend' : 'frontend';
}

function classCourseLevelType($model, $id) {
    $model = new $model;
    $modelVal = $model->findByAttributes(array('id' => $id));
    return ($modelVal->difficulty_type == '1' ? 'Beginner' : ($modelVal->difficulty_type == '2' ? 'Intermediate' : ($modelVal->difficulty_type == '3' ? 'Advance' : 'No data')));
}

function LevelCssClassName($model, $id) {
    $model = new $model;
    $modelVal = $model->findByAttributes(array('id' => $id));
    return ($modelVal->difficulty_type == '1' ? 'begginer' : ($modelVal->difficulty_type == '2' ? 'intermediate' : ($modelVal->difficulty_type == '3' ? 'advanced' : 'No data')));
}

function literalEndingTommorow($profiles, $userType, $getValue) {
    $date = date('Y-m-d');
    $classBatchData = array();
    $scheduleData = getCustomeScheduleClassBatchData($profiles, $userType, $getValue);
    usort($scheduleData, 'date_compare');
    $classBatchData = get_uniqueValue_in_array($scheduleData);
    return $classBatchData;
}

function getAllliteralEndingTommorow($profiles, $userType, $getValue, $limit) {
    $date = date('Y-m-d');
    $classBatchData = array();
    $scheduleData = getAllliteralEndingTommorowData($profiles, $userType, $getValue);
    usort($scheduleData, 'date_compare');
    $classBatchData = get_uniqueValue_in_array($scheduleData);
    return $classBatchData;
}

function getAllliteralEndingTommorowWorkshop($profiles, $userType, $getValue, $limit) {
    $leftjoin = '';
    $customeData = array();
    $stratdates = date("Y-m-d", strtotime(date('Y-m-d') . " +2 day"));
    $orderBy = '';
    $userid_type = ($userType != 'backend') ? 'users_id' : 'backend_user_id';
    if (!empty($getValue['priceorder'])) {
        $orderBy .=($getValue['priceorder'] == 1) ? '  scb.price ASC ,' : '  scb.price DESC , ';
    }
    if (!empty($getValue['mostpopular'])) {
        $orderBy .=($getValue['mostpopular'] == 1) ? '  sc.hits_counter DESC ' : '';
    }
    if (!empty($profiles) && !empty($userid_type)) {
        $where = ' sc.' . $userid_type . '=' . $profiles->user_id . ' AND sc.status="' . SkillConfig::STATUS_ACTIVE . '"  AND  ((scb.start_date<="' . $stratdates . '" AND scb.start_date>="' . date('Y-m-d') . '") OR (sbs.date<="' . $stratdates . '" AND sbs.date>="' . date('Y-m-d') . '") OR  (scbwm.weekly_monthly_start_date<="' . $stratdates . '" AND scbwm.weekly_monthly_start_date>="' . date('Y-m-d') . '"))';
    } else {
        $where = ' sc.status="' . SkillConfig::STATUS_ACTIVE . '" AND  ((scb.start_date<="' . $stratdates . '" AND scb.start_date>="' . date('Y-m-d') . '") OR (sbs.date<="' . $stratdates . '" AND sbs.date>="' . date('Y-m-d') . '") OR  (scbwm.weekly_monthly_start_date<="' . $stratdates . '" AND scbwm.weekly_monthly_start_date>="' . date('Y-m-d') . '"))';
    }
    if (isset($getValue['searchtype']) && $getValue['searchtype'] == SEARCH_TYPE_KIDS) {
        $leftjoin = 'LEFT JOIN skill_classes_target_audience scta  ON (t.classes_id=scta.classes_id)';
        $where .='  AND scta.target_audience_id=' . SEARCH_CLASS_KIDS_SET_DAY_SESSION;
    }

    if (empty($getValue['searchtype']) && isset($getValue['postwork']) && !empty($getValue['postwork'])) {
        $leftjoin = 'LEFT JOIN skill_classes_target_audience scta  ON (t.classes_id=scta.classes_id)';
        $where .='  AND scta.target_audience_id!=' . SEARCH_CLASS_KIDS_SET_DAY_SESSION;
    }

    if (!empty($getValue['type'])) {
        $classType = $getValue['type'] == 'curatedclasses' ? CURATED_CLASS_TYPE : LEAD_CLASS_TYPE;
        $where .='  AND sc.class_type_id=' . $classType;
    }

    if (!empty($getValue['location'])) {
        $location = getvenueIdByname($getValue['location']);
        $where .=' AND t.class_venue_id IN(' . $location . ')';
    }
    if (!empty($getValue['category'])) {
        $categoryArray = explode(',', $getValue['category']);
        $where .=' AND sc.category_id IN (' . $getValue['category'] . ')';
    }
    if (!empty($getValue['amountRange'])) {
        $price = explode(',', $getValue['amountRange']);
        $where .=' AND scb.price BETWEEN ' . $price[0] . ' AND ' . $price[1];
    }
    if (!empty($getValue['dateFrom']) AND !empty($getValue['dateto'])) {
        $dateFrom = $getValue['dateFrom'];
        $dateto = $getValue['dateto'];
        $where .=' AND (scb.start_date BETWEEN "' . $dateFrom . '" AND "' . $dateto . '" OR sbs.date BETWEEN "' . $dateFrom . '" AND "' . $dateto . '") ';
    }
    if (!empty($getValue['scheduleId'])) {
        $where .=' AND (DAYOFWEEK(scb.start_date) IN (' . $getValue['scheduleId'] . ') OR DAYOFWEEK(sbs.date) IN (' . $getValue['scheduleId'] . '))';
    }
    if (isset($getValue['postwork']) && !empty($getValue['postwork'])) {
        $where .=' AND (LEFT(scb.start_time,2) >=' . SEARCH_CLASS_POST_WORK_SET_START_TIME . ' AND LEFT(scb.start_time,2) <=' . SEARCH_CLASS_POST_WORK_SET_END_TIME . ' AND RIGHT(scb.start_time,2)="PM"  OR LEFT(sbs.start_time,2) >= ' . SEARCH_CLASS_POST_WORK_SET_START_TIME . ' AND LEFT(sbs.start_time,2) <= ' . SEARCH_CLASS_POST_WORK_SET_END_TIME . '  AND RIGHT(sbs.start_time,2) = "PM")';
    }
    if (!empty($getValue['learn'])) {
        $learn = $getValue['learn'];
        $vark = explode(' ', $learn);
        $endVal = end($vark);
        $endKey = key($vark);
        $localityVal = ($endKey > 0) ? $vark[$endKey - 1] . ' ' . $endVal : $endVal;
        $where .=' AND (sc.class_tag_description LIKE "%' . $learn . '%" OR sc.class_titile  LIKE "%' . $learn . '%" OR sc.class_description  LIKE "%' . $learn . '%" OR  sc.class_short_description  LIKE "%' . $learn . '%"  OR sc.class_outcome  LIKE "%' . $learn . '%" OR sc.class_prerequisites  LIKE "%' . $learn . '%" OR scv.venue_locality  LIKE "%' . $localityVal . '%")';
    }
    $classCommand = Yii::app()->db->createCommand();
    $classCommand->select = ('sc.class_seo_title,t.class_venue_id,scbwm.weekly_monthly_start_date,scb.price,sc.hits_counter,sbs.date,scb.start_date,sc.class_type_id,sc.class_titile,scb.classes_id, sc.users_id,sc.backend_user_id');
    $classCommand->from('skill_class_with_venue t left join skill_class_venue scv on (t.class_venue_id=scv.id) LEFT JOIN skill_classes sc ON (sc.id=t.classes_id) LEFT JOIN  skill_class_batch scb ON (scb.classes_id=t.classes_id AND scb.class_venue_id=t.class_venue_id) LEFT JOIN skill_batche_session sbs ON (scb.classes_id = sbs.classes_id) LEFT JOIN skill_classbatchweelymonthly scbwm ON (scb.classes_id = scbwm.classes_id) ' . $leftjoin);
    $classCommand->where($where);
    $classCommand->order($orderBy);
    if (!empty($limit)) {
        $classCommand->limit($limit);
    }
    $classDatas = $classCommand->queryAll();
    if (!empty($classDatas)) {
        foreach ($classDatas as $classData) {
            if (strtotime($classData['start_date'])<= strtotime($stratdates) AND strtotime($classData['start_date'])>= strtotime(date('Y-m-d'))) {
                $customeData[] = array('id' => $classData['classes_id'],
                    'remove_id' => $classData['classes_id'] . '-' . $classData['class_venue_id'],
                    'price' => $classData['price'],
                    'class_seo_title' => $classData['class_seo_title'],
                    'hits_counter' => $classData['hits_counter'],
                    'front-user' => $classData['users_id'],
                    'backend-user' => $classData['backend_user_id'],
                    'class_type_id' => $classData['class_type_id'],
                    'classes_id' => $classData['classes_id'], 'class_venue_id' => $classData['class_venue_id'],
                    'class_titile' => $classData['class_titile'], 'start_date' => $classData['start_date']);
            } else if (strtotime($classData['start_date']) < strtotime(date('Y-m-d')) && strtotime($classData['date']) >= strtotime(date('Y-m-d'))) {
                $customeData[] = array('id' => $classData['classes_id'],
                    'remove_id' => $classData['classes_id'] . '-' . $classData['class_venue_id'],
                    'price' => $classData['price'], 'hits_counter' => $classData['hits_counter'],
                    'front-user' => $classData['users_id'],
                    'class_seo_title' => $classData['class_seo_title'],
                    'backend-user' => $classData['backend_user_id'], 'class_venue_id' => $classData['class_venue_id'],
                    'class_type_id' => $classData['class_type_id'],
                    'classes_id' => $classData['classes_id'],
                    'class_titile' => $classData['class_titile'], 'start_date' => $classData['date']);
            } else if (strtotime($classData['start_date']) < strtotime(date('Y-m-d')) && strtotime($classData['weekly_monthly_start_date']) >= strtotime(date('Y-m-d')) && strtotime($classData['date']) < strtotime(date('Y-m-d'))) {
                $customeData[] = array('id' => $classData['classes_id'],
                    'remove_id' => $classData['classes_id'] . '-' . $classData['class_venue_id'],
                    'price' => $classData['price'], 'hits_counter' => $classData['hits_counter'],
                    'front-user' => $classData['users_id'], 'class_venue_id' => $classData['class_venue_id'],
                    'backend-user' => $classData['backend_user_id'],
                    'class_seo_title' => $classData['class_seo_title'],
                    'class_type_id' => $classData['class_type_id'],
                    'classes_id' => $classData['classes_id'],
                    'class_titile' => $classData['class_titile'],
                    'start_date' => $classData['weekly_monthly_start_date']);
            }
        }
    }
    return $customeData;
}

function getAllliteralEndingTommorowCourses($profiles, $userType, $getValue, $limit) {
    $courseArray = array();
    $leftjoin = '';
    $orderBy = '';
    $userid_type = ($userType != 'backend') ? 'users_id' : 'backend_user_id';
    $date = date("Y-m-d", strtotime(date('Y-m-d') . " +7 day"));   
    if (!empty($profiles) && !empty($userid_type)) {
        $where = 'sc.' . $userid_type . '=' . $profiles->user_id . '   AND sc.status="' . SkillConfig::STATUS_ACTIVE . '" AND scb.date_from>="' . $date . '" ';
    } else {
        $where = 'sc.status="' . SkillConfig::STATUS_ACTIVE . '"   AND scb.date_from>="' . $date . '" ';
    }
    if (isset($getValue['searchtype']) && $getValue['searchtype'] == SEARCH_TYPE_KIDS) {
        $leftjoin = 'LEFT JOIN skill_classes_target_audience scta  ON (t.courses_id=scta.courses_id)';
        $where .='  AND scta.target_audience_id=' . SEARCH_CLASS_KIDS_SET_DAY_SESSION;
    }

    if (empty($getValue['searchtype']) && isset($getValue['postwork']) && !empty($getValue['postwork'])) {
        $leftjoin = 'LEFT JOIN skill_classes_target_audience scta  ON (t.courses_id=scta.courses_id)';
        $where .='  AND scta.target_audience_id!=' . SEARCH_CLASS_KIDS_SET_DAY_SESSION;
    }


    if (!empty($getValue['location'])) {
        $location = $getValue['location'];
        $where .=' AND t.course_venue_id=' . $location;
    }

    if (!empty($getValue['priceorder'])) {
        $orderBy .=($getValue['priceorder'] == 1) ? ' scb.price ASC ,' : ' scb.price DESC , ';
    }
    if (!empty($getValue['mostpopular'])) {
        $orderBy .=($getValue['mostpopular'] == 1) ? '  sc.hits_counter DESC ' : '';
    }
    if (!empty($getValue['category'])) {
        $where .=' AND sc.category_id IN (' . $getValue['category'] . ')';
    }

    if (!empty($getValue['amountRange'])) {
        $price = explode(',', $getValue['amountRange']);
        $where .=' AND scb.price BETWEEN ' . $price[0] . ' AND ' . $price[1];
    }
    if (!empty($getValue['dateFrom']) AND !empty($getValue['dateto'])) {
        $dateFrom = $getValue['dateFrom'];
        $dateto = $getValue['dateto'];
        $where .=' AND scb.date_to BETWEEN "' . $dateFrom . '" AND "' . $dateto . '"';
    }
// scheduleId means this is weekend otherwise Kids Class course
    if (!empty($getValue['scheduleId'])) {
        $where .=' AND (DAYOFWEEK(scb.date_from) IN (' . $getValue['scheduleId'] . ')  OR  (DAYOFWEEK(cbds.date) IN (' . $getValue['scheduleId'] . '))   OR   scbds.schedule_id IN (' . shedule_session . '))';
    }
    if (isset($getValue['postwork']) && !empty($getValue['postwork'])) {
        $where .=' AND (LEFT(cbds.time_from,2)>=' . SEARCH_CLASS_POST_WORK_SET_START_TIME . ' AND LEFT(cbds.time_from,2)<=' . SEARCH_CLASS_POST_WORK_SET_END_TIME . ' AND RIGHT(cbds.time_from,2)="PM"   OR  LEFT(scbds.time_from,2)>=' . SEARCH_CLASS_POST_WORK_SET_START_TIME . ' AND LEFT(scbds.time_from,2)<=' . SEARCH_CLASS_POST_WORK_SET_END_TIME . ' AND RIGHT(scbds.time_from,2)="PM")';
    }
    if (!empty($getValue['learn'])) {
        $learn = $getValue['learn'];
        $vark = explode(' ', $learn);
        $endVal = end($vark);
        $endKey = key($vark);
        $localityVal = ($endKey > 0) ? $vark[$endKey - 1] . ' ' . $endVal : $endVal;
        $where .=' AND (sc.course_tag_description LIKE "%' . $learn . '%" OR sc.course_titile  LIKE "%' . $learn . '%" OR sc.course_description  LIKE "%' . $learn . '%" OR  sc.course_short_description  LIKE "%' . $learn . '%"  OR sc.course_outcome  LIKE "%' . $learn . '%" OR sc.course_prerequisites  LIKE "%' . $learn . '%" OR scv.venue_locality  LIKE "%' . $localityVal . '%")';
    }
    $command = Yii::app()->db->createCommand();
    $command->select('sc.course_seo_title,sc.hits_counter,scb.price,sc.users_id,sc.backend_user_id,scb.courses_id,sc.course_titile,scb.date_from,sc.course_type_id,scb.date_to,t.courses_id,t.course_venue_id');
    $command->from('skill_course_with_venue t left join skill_class_venue scv on (t.course_venue_id=scv.id)  left join skill_courses sc on (t.courses_id=sc.id) LEFT JOIN skill_course_batche scb ON (t.courses_id = scb.courses_id  AND t.course_venue_id=scb.course_venue_id) LEFT JOIN  skill_course_batche_date_session  cbds ON   (cbds.course_batche_id=scb.id  AND t.courses_id = cbds.courses_id) LEFT JOIN skill_course_batche_day_session scbds ON (scbds.course_batche_id=scb.id AND scb.courses_id = cbds.courses_id ) ' . $leftjoin);
    $command->where($where);
    $command->order($orderBy);
    if (!empty($limit)) {
        $command->limit($limit);
    }

    $rawDatas = $command->queryAll();
    foreach ($rawDatas as $rawData) {
        $courseArray[] = array('course_seo_title' => $rawData['course_seo_title'], 'id' => $rawData['courses_id'], 'remove_id' => $rawData['courses_id'] . '-' . $rawData['course_venue_id'], 'course_venue_id' => $rawData['course_venue_id'], 'price' => $rawData['price'], 'hits_counter' => $rawData['hits_counter'], 'front-user' => $rawData['users_id'], 'backend-user' => $rawData['backend_user_id'], 'course_type_id' => $rawData['course_type_id'], 'courses_id' => $rawData['courses_id'], 'course_titile' => $rawData['course_titile'], 'start_date' => $rawData['date_from'], 'end_date' => $rawData['date_to']);
    }
    usort($courseArray, 'date_compare');
    $courseArray = get_uniqueValue_in_array($courseArray);
  
    return $courseArray;
}

function get_uniqueValue_in_array($scheduleData) {
    $usedVals = array();
    $outArray = array();
    foreach ($scheduleData as $arrayItem) {
        if (!in_array($arrayItem['remove_id'], $usedVals)) {
            $outArray[] = $arrayItem;
            $usedVals[] = $arrayItem['remove_id'];
        }
    }
    return $outArray;
}

function getCustomeScheduleClassBatchData($profiles, $userType, $getValue) {
    $leftjoin = '';
    $customeData = array();
    $stratdates = date("Y-m-d");
    $orderBy = '';
    $userid_type = ($userType != 'backend') ? 'users_id' : 'backend_user_id';
    if (!empty($getValue['priceorder'])) {
        $orderBy .=($getValue['priceorder'] == 1) ? ' scb.price ASC ,' : ' scb.price DESC , ';
    }
    if (!empty($getValue['mostpopular'])) {
        $orderBy .=($getValue['mostpopular'] == 1) ? '  sc.hits_counter DESC ' : '';
    }
    if (!empty($profiles) && !empty($userid_type)) {
        $where = ' sc.' . $userid_type . '=' . $profiles->user_id . ' AND sc.status="' . SkillConfig::STATUS_ACTIVE . '"  AND  (scb.start_date>="' . $stratdates . '" OR sbs.date>="' . $stratdates . '" OR  scbwm.weekly_monthly_start_date>="' . $stratdates . '")';
    } else {
        $where = ' sc.status="' . SkillConfig::STATUS_ACTIVE . '" AND  (scb.start_date>="' . $stratdates . '" OR sbs.date>="' . $stratdates . '" OR  scbwm.weekly_monthly_start_date>="' . $stratdates . '")';
    }
    if (isset($getValue['searchtype']) && $getValue['searchtype'] == SEARCH_TYPE_KIDS) {
        $leftjoin = 'LEFT JOIN skill_classes_target_audience scta  ON (t.classes_id=scta.classes_id)';
        $where .='  AND scta.target_audience_id=' . SEARCH_CLASS_KIDS_SET_DAY_SESSION;
    }

    if (empty($getValue['searchtype']) && isset($getValue['postwork']) && !empty($getValue['postwork'])) {
        $leftjoin = 'LEFT JOIN skill_classes_target_audience scta  ON (t.classes_id=scta.classes_id)';
        $where .='  AND scta.target_audience_id!=' . SEARCH_CLASS_KIDS_SET_DAY_SESSION;
    }

    if (!empty($getValue['type'])) {
        $classType = ($getValue['type'] == 'curatedclasses' || $getValue['type'] == 'exclusives') ? CURATED_CLASS_TYPE : LEAD_CLASS_TYPE;
        $where .='  AND sc.class_type_id=' . $classType;
    }

    if (!empty($getValue['location'])) {
        $location = getvenueIdByname($getValue['location']);
        $where .=' AND t.class_venue_id IN(' . $location . ')';
    }
    if (!empty($getValue['category'])) {
        $categoryArray = explode(',', $getValue['category']);
        $where .=' AND sc.category_id IN (' . $getValue['category'] . ')';
    }
    if (!empty($getValue['amountRange'])) {
        $price = explode(',', $getValue['amountRange']);
        $where .=' AND scb.price BETWEEN ' . $price[0] . ' AND ' . $price[1];
    }
    if (!empty($getValue['dateFrom']) AND !empty($getValue['dateto'])) {
        $dateFrom = $getValue['dateFrom'];
        $dateto = $getValue['dateto'];
        $where .=' AND (scb.start_date BETWEEN "' . $dateFrom . '" AND "' . $dateto . '" OR sbs.date BETWEEN "' . $dateFrom . '" AND "' . $dateto . '") ';
    }
    if (!empty($getValue['scheduleId'])) {
        $where .=' AND (DAYOFWEEK(scb.start_date) IN (' . $getValue['scheduleId'] . ') OR DAYOFWEEK(sbs.date) IN (' . $getValue['scheduleId'] . '))';
    }

    if (isset($getValue['postwork']) && !empty($getValue['postwork'])) {
        $where .=' AND (LEFT(scb.start_time,2) >=' . SEARCH_CLASS_POST_WORK_SET_START_TIME . ' AND LEFT(scb.start_time,2) <=' . SEARCH_CLASS_POST_WORK_SET_END_TIME . ' AND RIGHT(scb.start_time,2)="PM"  OR LEFT(sbs.start_time,2) >= ' . SEARCH_CLASS_POST_WORK_SET_START_TIME . ' AND LEFT(sbs.start_time,2) <= ' . SEARCH_CLASS_POST_WORK_SET_END_TIME . '  AND RIGHT(sbs.start_time,2) = "PM")';
    }
    if (!empty($getValue['learn'])) {
        $learn = $getValue['learn'];
        $vark = explode(' ', $learn);
        $endVal = end($vark);
        $endKey = key($vark);
        $localityVal = ($endKey > 0) ? $vark[$endKey - 1] . ' ' . $endVal : $endVal;
        $where .=' AND (sc.class_tag_description LIKE "%' . $learn . '%" OR sc.class_titile  LIKE "%' . $learn . '%" OR sc.class_description  LIKE "%' . $learn . '%" OR  sc.class_short_description  LIKE "%' . $learn . '%"  OR sc.class_outcome  LIKE "%' . $learn . '%" OR sc.class_prerequisites  LIKE "%' . $learn . '%" OR scv.venue_locality  LIKE "%' . $localityVal . '%")';
    }
    $classCommand = Yii::app()->db->createCommand();
    $classCommand->select = ('sc.class_seo_title,t.class_venue_id,scbwm.weekly_monthly_start_date,scb.price,sc.hits_counter,sbs.date,scb.start_date,sc.class_type_id,sc.class_titile,scb.classes_id, sc.users_id,sc.backend_user_id');
    $classCommand->from('skill_class_with_venue t left join skill_class_venue scv on (t.class_venue_id=scv.id) LEFT JOIN skill_classes sc ON (sc.id=t.classes_id) LEFT JOIN  skill_class_batch scb ON (scb.classes_id=t.classes_id AND scb.class_venue_id=t.class_venue_id) LEFT JOIN skill_batche_session sbs ON (t.classes_id = sbs.classes_id) LEFT JOIN skill_classbatchweelymonthly scbwm ON (t.classes_id = scbwm.classes_id) ' . $leftjoin);
    $classCommand->where($where);
    $classCommand->order($orderBy);
    //echo $classCommand->getText();die;
    $classDatas = $classCommand->queryAll();
    if (!empty($classDatas)) {
        foreach ($classDatas as $classData) {
            if (strtotime($classData['start_date']) >= strtotime($stratdates)) {
                $customeData[] = array('id' => $classData['classes_id'],
                    'remove_id' => $classData['classes_id'] . '-' . $classData['class_venue_id'],
                    'price' => $classData['price'],
                    'class_seo_title' => $classData['class_seo_title'],
                    'hits_counter' => $classData['hits_counter'],
                    'front-user' => $classData['users_id'],
                    'backend-user' => $classData['backend_user_id'],
                    'class_type_id' => $classData['class_type_id'],
                    'classes_id' => $classData['classes_id'], 'class_venue_id' => $classData['class_venue_id'],
                    'class_titile' => $classData['class_titile'], 'start_date' => $classData['start_date']);
            } else if (strtotime($classData['start_date']) < strtotime($stratdates) && strtotime($classData['date']) >= strtotime($stratdates)) {
                $customeData[] = array('id' => $classData['classes_id'],
                    'remove_id' => $classData['classes_id'] . '-' . $classData['class_venue_id'],
                    'price' => $classData['price'], 'hits_counter' => $classData['hits_counter'],
                    'front-user' => $classData['users_id'],
                    'class_seo_title' => $classData['class_seo_title'],
                    'backend-user' => $classData['backend_user_id'], 'class_venue_id' => $classData['class_venue_id'],
                    'class_type_id' => $classData['class_type_id'],
                    'classes_id' => $classData['classes_id'],
                    'class_titile' => $classData['class_titile'], 'start_date' => $classData['date']);
            } else if (strtotime($classData['start_date']) < strtotime($stratdates) && strtotime($classData['weekly_monthly_start_date']) >= strtotime($stratdates) && strtotime($classData['date']) < strtotime($stratdates)) {
                $customeData[] = array('id' => $classData['classes_id'],
                    'remove_id' => $classData['classes_id'] . '-' . $classData['class_venue_id'],
                    'price' => $classData['price'], 'hits_counter' => $classData['hits_counter'],
                    'front-user' => $classData['users_id'], 'class_venue_id' => $classData['class_venue_id'],
                    'backend-user' => $classData['backend_user_id'],
                    'class_seo_title' => $classData['class_seo_title'],
                    'class_type_id' => $classData['class_type_id'],
                    'classes_id' => $classData['classes_id'],
                    'class_titile' => $classData['class_titile'],
                    'start_date' => $classData['weekly_monthly_start_date']);
            }
        }
    }

    return $customeData;
}

function getvenueIdByname($venue) {
    $venueId = '';
    $venueName = ClassVenue::model()->findByPk($venue);
    $venue_locality = ClassVenue::model()->findAllByAttributes(array('venue_locality' => $venueName->venue_locality));
    if (!empty($venue_locality)) {
        foreach ($venue_locality as $venue) {
            $venueId .= $venue['id'] . ',';
        }
    }
    return substr($venueId, 0, -1);
}

function literalendingtommorowValiadte($allClassCourseInfo) {
    $stratDate = array();
    $stratdates = date('Y-m-d');
    $addTwosdaysIndate = date("Y-m-d", strtotime("$stratdates +2 day"));
    foreach ($allClassCourseInfo as $classDetail) {
        if ($classDetail['start_date'] <= $addTwosdaysIndate) {
            $stratDate = $classDetail['start_date'];
        }
    }
    return $stratDate;
}

function substrclasscourname($courseName) {
    return (strlen($courseName) > 14) ? substr($courseName, 0, 10) . ' ..' : $courseName;
}

/* get date weekly */

function getDateBatchWeekly($startdate) {
    $startDateUnix = strtotime($startdate);
    $currentDateUnix = strtotime(CURRENT_DATE);
    $endDateUnix = strtotime('+1 month', $currentDateUnix);
    $currentDateUnix = $startDateUnix;
    $weekNumbers = array();
    while ($currentDateUnix < $endDateUnix) {
        $weekDates[] = date('Y-m-d', $currentDateUnix);
        $currentDateUnix = strtotime('+1 week', $currentDateUnix);
    }
    return $weekDates;
}

function getCMSConetnt($id) {
    $cmsContent = CmsContent::model()->findByAttributes(array('id' => $id));
    return $cmsContent;
}

function getEmailbyuserId($model, $id) {
    $model = new $model;
    $model = $model->findByAttributes(array('id' => $id));
    return $model;
}

function getWorkNoshopimage($imageName) {
    return getRequestbaseUrl() . '/upload/' . $imageName;
}

function getClassCoursCharLimit($name) {
    if (strlen($name) > 16) {
        $substart = substr($name, 0, 20);
        $endstirng = substr($name, 20, 50);
        $doted = (strlen($name) > 20) ? '...' : '';
        $name = (!empty($endstirng)) ? $substart . $doted : $substart;
    }
    return $name;
}

function manageClassByuser($classType, $location) {
    $classArray = array();
    $criteria = new CDbCriteria();
    $criteria->addCondition('users_id=' . getLoginUserId());
    if (!empty($classType) || !empty($location)) {
        $date = date('Y-m-d');
        $criteria->select = 't.*,B.start_date,p.classes_id,p.class_venue_id';
        $criteria->join = 'LEFT JOIN skill_class_with_venue p ON  (t.id = p.classes_id) LEFT JOIN skill_class_batch B ON (t.id = B.classes_id)';

        if (!empty($location)) {
            $criteria->addCondition('p.class_venue_id = "' . $location . '"');
        }
        if ($classType == 1) {
            $criteria->addCondition('B.start_date="' . $date . '"');
        }
        if ($classType == 2) {
            $criteria->addCondition('B.start_date>"' . $date . '"');
        } if ($classType == 3) {
            $criteria->addCondition('B.start_date<"' . $date . '"');
        }
        $criteria->group = 'B.classes_id';
    }
    $classdata = Classes::model()->findAll($criteria);
    foreach ($classdata as $rawData) {
        $classArray[] = array('id' => $rawData->id, 'class_seo_title' => $rawData['class_seo_title'], 'hits_counter' => $rawData->hits_counter, 'status' => $rawData->status, 'class_type_id' => $rawData->class_type_id, 'classes_id' => $rawData->id, 'class_titile' => $rawData->class_titile);
    }

    return $classArray;
}

function manageCourseByuser($classType, $location) {
    $courseArray = array();
    $criteria = new CDbCriteria();
    $criteria->addCondition('users_id=' . getLoginUserId());
    if (!empty($classType) || !empty($location)) {
        $date = date('Y-m-d');
        $criteria->select = 't.*,B.date_from,p.courses_id,p.course_venue_id';
        $criteria->join = 'LEFT JOIN skill_course_with_venue p ON  (t.id = p.courses_id) LEFT JOIN skill_course_batche B ON (t.id = B.courses_id)';
        if (!empty($location)) {
            $criteria->addCondition('p.course_venue_id = "' . $location . '"');
        }
        if ($classType == 1) {
            $criteria->addCondition('B.date_from<="' . $date . '"');
            $criteria->addCondition('B.date_to>="' . $date . '"');
        }
        if ($classType == 2) {
            $criteria->addCondition('B.date_from>"' . $date . '"');
        } if ($classType == 3) {
            $criteria->addCondition('B.date_from<"' . $date . '"');
        }
        $criteria->group = 'B.courses_id';
    }
    $coursedata = Courses::model()->findAll($criteria);
    foreach ($coursedata as $rawData) {
        $courseArray[] = array('id' => $rawData->id, 'course_seo_title' => $rawData['course_seo_title'], 'hits_counter' => $rawData->hits_counter, 'status' => $rawData->status, 'course_type_id' => $rawData->course_type_id, 'course_id' => $rawData->id, 'course_titile' => $rawData->course_titile);
    }
    return $courseArray;
}

function workshoponHomePage($getValue) {
    $customeData = array();
    $stratdates = date("Y-m-d");
    $orderBy = 't.go_to_home DESC';
    $where = 't.status="' . SkillConfig::STATUS_ACTIVE . '"  AND  (scb.start_date>="' . $stratdates . '" OR sbs.date>="' . $stratdates . '" OR  scbwm.weekly_monthly_start_date>="' . $stratdates . '")';
    // also change the condion after loop < to >
    if (!empty($getValue['type'])) {
        $classType = $getValue['type'] == 'curatedclasses' ? CURATED_CLASS_TYPE : LEAD_CLASS_TYPE;
        $where .='  AND t.class_type_id=' . $classType;
    }
    $classCommand = Yii::app()->db->createCommand();
    $classCommand->select = ('t.class_seo_title,scwv.class_venue_id, scbwm.weekly_monthly_start_date,scb.price,t.hits_counter,sbs.date,scb.start_date,t.class_type_id,t.class_titile,scb.classes_id, t.users_id,t.backend_user_id');
    $classCommand->from('skill_classes t LEFT JOIN skill_class_batch scb ON (t.id = scb.classes_id)  LEFT JOIN skill_batche_session sbs ON (scb.classes_id = sbs.classes_id) LEFT JOIN skill_classbatchweelymonthly scbwm ON (scb.classes_id = scbwm.classes_id) LEFT JOIN skill_class_with_venue scwv ON (t.id = scwv.classes_id)');
    $classCommand->where($where);
    $classCommand->order($orderBy);
    $classDatas = $classCommand->queryAll();
    if (!empty($classDatas)) {
        foreach ($classDatas as $classData) {
            if (strtotime($classData['start_date']) <= strtotime($stratdates) OR strtotime($classData['start_date']) >= strtotime($stratdates)) {
                $customeData[] = array('id' => $classData['classes_id'],
                    'remove_id' => $classData['classes_id'],
                    'price' => $classData['price'],
                    'hits_counter' => $classData['hits_counter'],
                    'front-user' => $classData['users_id'],
                    'backend-user' => $classData['backend_user_id'],
                    'class_type_id' => $classData['class_type_id'],
                    'class_seo_title' => $classData['class_seo_title'],
                    'classes_id' => $classData['classes_id'], 'class_venue_id' => $classData['class_venue_id'],
                    'class_titile' => $classData['class_titile'], 'start_date' => $classData['start_date']);
            } else if (strtotime($classData['start_date']) < strtotime($stratdates) && strtotime($classData['date']) >= strtotime($stratdates)) {
                $customeData[] = array('id' => $classData['classes_id'],
                    'remove_id' => $classData['classes_id'],
                    'price' => $classData['price'], 'hits_counter' => $classData['hits_counter'],
                    'front-user' => $classData['users_id'],
                    'class_seo_title' => $classData['class_seo_title'],
                    'backend-user' => $classData['backend_user_id'], 'class_venue_id' => $classData['class_venue_id'],
                    'class_type_id' => $classData['class_type_id'],
                    'classes_id' => $classData['classes_id'],
                    'class_titile' => $classData['class_titile'], 'start_date' => $classData['date']);
            } else if (strtotime($classData['start_date']) < strtotime($stratdates) && strtotime($classData['weekly_monthly_start_date']) >= strtotime($stratdates) && strtotime($classData['date']) < strtotime($stratdates)) {
                $customeData[] = array('id' => $classData['classes_id'],
                    'remove_id' => $classData['classes_id'],
                    'price' => $classData['price'], 'hits_counter' => $classData['hits_counter'],
                    'front-user' => $classData['users_id'], 'class_venue_id' => $classData['class_venue_id'],
                    'backend-user' => $classData['backend_user_id'],
                    'class_type_id' => $classData['class_type_id'],
                    'class_seo_title' => $classData['class_seo_title'],
                    'classes_id' => $classData['classes_id'],
                    'class_titile' => $classData['class_titile'], 'start_date' => $classData['weekly_monthly_start_date']);
            }
        }
    }
    //usort($customeData, 'date_compare');
    $customeData = get_uniqueValue_in_array($customeData);

    return $customeData;
}

function runningCourseHomepage() {
    $courseArray = array();
    $orderBy = 'sc.go_to_home DESC';
    $date = date('Y-m-d');
    $where = 'sc.status="' . SkillConfig::STATUS_ACTIVE . '" AND scb.date_to>="' . $date . '"';
    $command = Yii::app()->db->createCommand();
    $command = Yii::app()->db->createCommand();
    $command->select('sc.course_seo_title, sc.hits_counter, scb.price, sc.users_id, sc.backend_user_id, scb.courses_id, sc.course_titile, scb.date_from, sc.course_type_id, scb.date_to, t.courses_id, t.course_venue_id');
    $command->from('skill_course_with_venue t inner join skill_courses sc on (t.courses_id=sc.id) right JOIN skill_course_batche scb ON (t.courses_id = scb.courses_id AND t.course_venue_id=scb.course_venue_id)');
    $command->where($where);
    $command->group('scb.course_venue_id');
    $command->having('COUNT(scb.courses_id) >= 2');
    $command->order($orderBy);
    $command->limit('12');
    $rawDatas = $command->queryAll();
    foreach ($rawDatas as $rawData) {
        $courseArray[] = array('course_seo_title' => $rawData['course_seo_title'], 'id' => $rawData['courses_id'], 'remove_id' => $rawData['courses_id'], 'course_venue_id' => $rawData['course_venue_id'], 'price' => $rawData['price'], 'hits_counter' => $rawData['hits_counter'], 'front-user' => $rawData['users_id'], 'backend-user' => $rawData['backend_user_id'], 'course_type_id' => $rawData['course_type_id'], 'courses_id' => $rawData['courses_id'], 'course_titile' => $rawData['course_titile'], 'start_date' => $rawData['date_from'], 'end_date' => $rawData['date_to']);
    }
    //usort($courseArray, 'date_compare');
    // $courseArray = get_uniqueValue_in_arrayhome($courseArray);/

    return $courseArray;
}

function get_uniqueValue_in_arrayhome($scheduleData) {
    $usedVals = array();
    $outArray = array();
    foreach ($scheduleData as $arrayItem) {
        if (!in_array($arrayItem['remove_id'], $usedVals)) {
            $outArray[] = $arrayItem;
            $usedVals[] = $arrayItem['remove_id'];
        }
    }
    return $outArray;
}
